package com.shanghaionstar.user;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.map.util.ToastUtil;
import com.onstar.cn.smart.BaseResponse;
import com.onstar.cn.weight.DeleteEditText;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.MoreActivity;
import com.shanghaionstar.user.iview.IChangeContactView;
import com.shanghaionstar.user.presenter.ChangeContactPresenter;
import com.shanghaionstar.weight.CommonProgressButton;
import com.shanghaionstar.weight.TopLayout;

import java.util.regex.Pattern;



/**
 * Created by 7828wc on 16/7/18.
 * 更改联系地址界面
 */
public class ChangeContactAddressFragment extends BaseFragment implements IChangeContactView, AdapterView.OnItemSelectedListener {

    private ChangeContactPresenter presenter;
    @FindViewById
    private Spinner spinner_province;
    @FindViewById
    private TopLayout top_layout;

    @FindViewById
    private DeleteEditText edit_city, edit_address, edit_code;

    @FindViewById
    private CommonProgressButton btn_submit;

    @Override
    public int getLayoutId() {
        return R.layout.more_change_contact;
    }

    //
    String provinceKey;
    String provinceValue;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        presenter = new ChangeContactPresenter(((MoreActivity) getActivity()).getScheduler());
        presenter.setView(ChangeContactAddressFragment.this);
        top_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                back();
            }
        });
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String cityStr = edit_city.getText().toString();
                String addressStr = edit_address.getText().toString();
                String postCode = edit_code.getText().toString();
                //校验
                if (TextUtils.isEmpty(provinceKey) || TextUtils.isEmpty(cityStr) || TextUtils.isEmpty(addressStr) || TextUtils.isEmpty(postCode)) {
                    ToastUtil.show(getActivity(), "请填写完整信息");
                    return;
                }
                if (!isPostCode(postCode)) {
                    ToastUtil.show(getActivity(), "请填写有效的邮政编码");
                    return;
                }
                presenter.setUserInfo(provinceKey, cityStr, addressStr, postCode);
                presenter.start();
            }
        });


        initData();//
    }

    /**
     * 初始化数据
     */
    private void initData() {
        //接收数据
        provinceValue = getArguments().getString("province");
        String cityStr = getArguments().getString("city");
        String addressStr = getArguments().getString("address");
        String codeStr = getArguments().getString("code");
        if (!CommonUtil.isNull(provinceValue)) {
            //显示默认值
            setSpinnerItemSelectedByValue(spinner_province, provinceValue);
        }
        edit_city.setText(cityStr);
        edit_address.setText(addressStr);
        edit_code.setText(codeStr);


        //设置监听
        spinner_province.setOnItemSelectedListener(this);
    }


    @Override
    public void setLoading(boolean isLoading) {

    }

    @Override
    public void onResponseError(OnStarException e) {

    }

    @Override
    public void onReponseSuccess(BaseResponse object) {
        if (object.code.equals("E0000")) {
            if (baseActivity instanceof MoreActivity) {
                ((MoreActivity) baseActivity).setProvince(provinceValue);
                ((MoreActivity) baseActivity).setCity(edit_city.getText().toString());
                ((MoreActivity) baseActivity).setAddress(edit_address.getText().toString());
                ((MoreActivity) baseActivity).setCode(edit_code.getText().toString());
            }
            ToastView toastView = new ToastView(getActivity());
            toastView.showToast("保存信息成功");
            back();
        }
    }

    @Override
    public Activity onActivity() {
        return getActivity();
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String[] provinceKeys = getResources().getStringArray(R.array.provinces_key);
        String[] provinceValues = getResources().getStringArray(R.array.provinces_value);
        provinceKey = provinceKeys[position];
        provinceValue = provinceValues[position];
        Log.e("onItemSelected_keys", provinceValue);
        Log.e("onItemSelected_values", provinceValue);

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }


    /**
     * 匹配中国邮政编码
     *
     * @param postCode 邮政编码
     * @return 验证成功返回true，验证失败返回false
     */
    public boolean isPostCode(String postCode) {
        String reg = "[1-9]\\d{5}";
        return Pattern.matches(reg, postCode);
    }

    /**
     * 根据值, 设置spinner默认选中:
     *
     * @param spinner
     * @param value
     */
    public static void setSpinnerItemSelectedByValue(Spinner spinner, String value) {
        SpinnerAdapter apsAdapter = spinner.getAdapter(); //得到SpinnerAdapter对象
        int k = apsAdapter.getCount();
        for (int i = 0; i < k; i++) {
            if (value.equals(apsAdapter.getItem(i).toString())) {
                spinner.setSelection(i, true);// 默认选中项
                break;
            }
        }
    }
}
